var common = require("../../utils/Conmon.js");
var appData = getApp().globalData;
// pages/returngoods/returngoods.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['仅退款，无需退货', '退款并向商家退货'],
    index: 0,
    StatusStr: '',
    OrderDetails: {},
    GoodsNum: 0,
    PayAmount: 0,
    YunMoney: 0,
    OrderID: '',
    CreateTime: '',
    PayTime: '',
    ReturnReason: '',
    PhotoVoucher: '',
    AskUser: 0,
    ExpressCompany: '',
    ExpressCode: '',
    ExpressNo: '',
    PartOrderRefundEnable: false,
    GoodsList: [],
    pids: [0],
    TempPics: [],
    TempPicImgs: [],
    UnionShopName: "官方自营",
    ShopType: "自营",
    selectAll: false,
    shopID: 0,
    OrderInfo: null,
    Companys: [],
    Express: [],
    expressIndex: 0
  },

  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  bindCompanysChange: function (e) {
    var com = this.data.Express[e.detail.value];
    this.setData({
      ExpressCode: com.ExpressCode,
      ExpressCompany: com.Company,
      expressIndex: e.detail.value
    })

  },
  selectall: function (e) {
    var selectAll = this.data.selectAll;
    var list = this.data.OrderDetails;
    var pids = [];
    var order = this.data.OrderInfo;
    var yunMoney = 0;
    var num = 0;
    var paymoney = order.PayAmount;
    if (selectAll == true) {
      for (var i = 0, len = list.length; i < len; i++) {
        list[i].selected = false;
        paymoney = 0;
      }
    } else {
      for (var i = 0, len = list.length; i < len; i++) {
        list[i].selected = true;
        pids.push(list[i].GoodsID);
        num += list[i].Num;
      }
      if (order.OrderStatus == 2) {
        yunMoney = order.YunMoney;
      }
    }
    this.setData({
      selectAll: !selectAll,
      OrderDetails: list,
      pids: pids,
      YunMoney: yunMoney,
      GoodsNum: num,
      PayAmount: paymoney,
    });
  },

  //上传文件
  upload_file: function (url, filePath, name, success, fail) {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      formData: {
        'customerid': appData.custID,
        'userid': wx.getStorageSync('UserInfo').UserID,
        'imageType': 0,
        'imageSize': 0,
        'isWeixin': 0
      }, // HTTP 请求中其他额外的参数
      header: {
        'content-type': 'multipart/form-data'
      }, // 设置请求的 header
      success: function (res) {
        if (res.statusCode == 200 && !res.data.result_code) {
          typeof success == "function" && success(res.data);
        } else {
          typeof fail == "function" && fail(res);
        }
      },
      fail: function (res) {

        typeof fail == "function" && fail(res);
      }
    })
  },
  /**
   * 上传凭证
   */

  onUploadPics: function (e) {
    var that = this;
    wx.chooseImage({
      count: 3, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var arr = that.data.TempPics;
        var arrImg = that.data.TempPicImgs;
        if (arr.length >= 3) {
          wx.showToast({
            title: '最多上传3张图片',
            duration: 2000
          })
          return false;
        }
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          that.upload_file(appData.upFileUrl + 'Baidu/AliyunUpload', res.tempFilePaths[i], 'photo',
            function (res) {
              //调用上传文件成功
              //console.log(res);
              var resData = JSON.parse(res)
              arr.push(resData.dataUrl);
              arrImg.push(resData.url);
              that.setData({
                TempPics: arr,
                TempPicImgs: arrImg
              })
            });

        }



      }
    })
  },

  /**
   * 删除凭证
   */
  onDelPic: function (e) {
    var arr = new Array();
    var arrImg = new Array();
    arr = this.data.TempPics;
    arrImg = this.data.TempPicImgs;
    for (var i = 0; i < arr.length; i++) {
      if (i == e.target.id) {
        arr.splice(i, 1);
        arrImg.splice(i, 1);
        break;
      }
    }
    this.setData({
      TempPics: arr,
      TempPicImgs: arrImg
    })
  },

  /**
   * 获取物流名称
   */
  onExpressCompanyInput: function (e) {
    this.setData({
      ExpressCompany: e.detail.value
    })
  },

  /**
   * 获取物流单号
   */
  onExpressNoInput: function (e) {
    this.setData({
      ExpressNo: e.detail.value
    })
  },

  /**
   * 获取退款原因说明
   */
  onReturnReasonInput: function (e) {
    this.setData({
      ReturnReason: e.detail.value
    })
  },

  /**
   * 勾选要申请退款的商品
   */
  checkboxChange: function (e) {
    this.setData({
      pids: e.detail.value
    })

    var pids = this.data.pids;
    var len = this.data.pids.length;
    var list = this.data.OrderDetails;
    var selectall = false;
    var num = 0;
    var money = 0;
    var yunmoney = 0;

    for (var i = 0, lenI = list.length; i < lenI; i++) {
      var index = pids.indexOf(list[i].GoodsID + "");
      if (index > -1) {
        list[i].selected = true;
        num += parseInt(list[i].Num);
        money += parseFloat(list[i].Price);
      } else {
        list[i].selected = false;
      }
    }

    if (len == list.length) {
      selectall = true;
      money = parseFloat(this.data.OrderInfo.PayAmount);
      yunmoney = this.data.OrderInfo.YunMoney;
    } else {
      selectall = false;
      yunmoney = 0;
    }

    this.setData({
      selectAll: selectall,
      GoodsNum: num,
      OrderDetails: list,
      PayAmount: money.toFixed(2),
      YunMoney: yunmoney
    });

  },

  /**
   * 申请退款
   */
  onSubmitApply: function (event) {
    var that = this;
    if (this.data.PartOrderRefundEnable) {
      if (this.data.pids.length == 0) {
        wx.showToast({
          title: '请勾选退款商品',
          duration: 2000
        })
        return false;
      }
    }
    if (this.data.index == 1) {
      if (this.data.ExpressCompany == '') {
        wx.showToast({
          title: '请选择快递公司',
          duration: 2000
        })
        return false;
      }
      if (this.data.ExpressNo == '') {
        wx.showToast({
          title: '请填写物流单号',
          duration: 2000
        })
        return false;
      }
    }
    if (this.data.ReturnReason == '') {
      wx.showToast({
        title: '请填写退款原因',
        duration: 2000
      })
      return false;
    }
    if (this.data.TempPics.length > 3) {
      wx.showToast({
        title: '最多上传3张凭证',
        duration: 2000
      })
      return false;
    }

    var globalData = getApp().globalData;
    var custId = globalData.custID;
    var res = wx.getStorageSync('UserInfo');
    var userId = res.UserID;
    var url = globalData.apiurl + '/order/api/OrderInfo/RefundOrder';

    var d = new Object();
    d.CustID = custId;
    d.ReturnNo = '';
    if (this.data.index == 0) {
      d.ReturnType = 1;
    } else {
      d.ReturnType = 2;
    }
    d.RetuenMoney = this.data.PayAmount;
    d.ReturnReason = this.data.ReturnReason;
    d.ReturnRemark = '';
    if (this.data.TempPics.length == 0) {
      d.PhotoVoucher = '';
    } else {
      var parr = this.data.TempPics;
      d.PhotoVoucher = parr.join(',');
    }
    d.AskUser = userId;
    d.HandleStatus = 0;
    d.HandleUser = 0;
    d.OrderID = this.data.OrderID;
    d.unionStoreID = that.data.shopID;
    d.ExpressCompany = this.data.ExpressCompany;
    d.ExpressNo = this.data.ExpressNo;
    d.ExpressCode = this.data.ExpressCode;
    if (this.data.PartOrderRefundEnable) {
      //获取勾选的要退款的商品
      var gArr = new Array();
      for (var i = 0; i < this.data.GoodsList.length; i++) {
        for (var j = 0; j < this.data.pids.length; j++) {
          if (this.data.GoodsList[i].GoodsID == this.data.pids[j]) {
            gArr.push(this.data.GoodsList[i]);
          }
        }
      }
      d.ReturnGoodsInfoList = gArr;
    } else {
      d.ReturnGoodsInfoList = this.data.GoodsList;
    }

    wx.showModal({
      title: '申请退款',
      content: '确定申请退款吗？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: url,
            data: JSON.stringify(d),
            method: 'POST',
            header: {

              'X_ManuName': getApp().globalData.manuName
            },
            success: function (res) {
              if (res.data.code == 1200) {
                wx.showToast({
                  title: '申请退款成功',
                  duration: 2000
                })
                wx.switchTab({
                  url: '/pages/myorders/myorders',
                })
              }
            },
            fail: function () {
              wx.showToast({
                title: '申请退款失败',
                duration: 2000
              })
            },
            complete: function () {
              //complete
            }
          })
        }
      }
    })
  },
  bindExpress: function () {
    var that = this;
    var globalData = getApp().globalData;

    var url = globalData.apiurl + '/order/api/OrderInfo/GetAllExpressCompany';
    wx.request({
      url: url,
      data: {

      },
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'X_ManuName': globalData.manuName
      },
      success: function (res) {
        var d = res.data.content;
        var list = new Array();

        for (var i = 0; i < d.length; i++) {


          list.push(d[i].Company);
        }

        that.setData({
          Companys: list,
          Express: d
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    common.pageInit(function () { });
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    var that = this;
    that.bindExpress();
    that.setData({
      shopID: options.shopID
    });
    var globalData = getApp().globalData;
    var custId = globalData.custID;
    var url = globalData.apiurl + '/order/api/OrderInfo/GetEnableRefundProduct';

    wx.request({
      url: url,
      data: {
        "custId": custId,
        "orderId": options.OrderID,
        "unionStoreID": that.data.shopID
      },
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'X_ManuName': globalData.manuName
      },
      success: function (res) {
        var OrderInfo = res.data.content;
        getHtml(OrderInfo.CanRefundOrderDetails);
        var arr = new Array();
        for (var i = 0; i < OrderInfo.CanRefundOrderDetails.length; i++) {
          var Goods = new Object();
          Goods.CustID = OrderInfo.CanRefundOrderDetails[i].CustID;
          Goods.HandleStatus = 0;
          Goods.Sort = 0;
          Goods.ProductID = OrderInfo.CanRefundOrderDetails[i].ProductId;
          Goods.GoodsID = OrderInfo.CanRefundOrderDetails[i].GoodsID;
          Goods.ReturnOrderID = 0;
          arr.push(Goods);
          OrderInfo.CanRefundOrderDetails[i].selected = true;
        }
        var PartEnable = false;
        if (OrderInfo.OrderRefundSet != null) {
          PartEnable = OrderInfo.OrderRefundSet.PartOrderRefundEnable;
        }
        that.setData({
          StatusStr: OrderInfo.StatusStr,
          OrderDetails: OrderInfo.CanRefundOrderDetails,
          GoodsNum: OrderInfo.GoodsNum,
          PayAmount: OrderInfo.PayAmount,
          YunMoney: OrderInfo.YunMoney,
          OrderID: OrderInfo.OrderID,
          CreateTime: OrderInfo.CreateTime,
          PayTime: OrderInfo.PayTime,
          PartOrderRefundEnable: PartEnable,
          GoodsList: arr,
          UnionShopName: OrderInfo.UnionStoreID == 0 ? "官方自营" : OrderInfo.UnionShopName,
          ShopType: OrderInfo.UnionStoreID == 0 ? "自营" : "商家",
          OrderInfo: OrderInfo,
          selectAll: false,
        });

        that.selectall();
        wx.hideLoading();
      },
      fail: function () {
        wx.hideLoading();
        wx.showToast({
          title: '获取订单详情失败',
          duration: 2000
        })
      },
      complete: function () {
        //complete
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

function getHtml(d) {
  if (d.length > 0) {
    for (var j = 0; j < d.length; j++) {
      if (d[j].acitivtys != null && d[j].acitivtys != "") {
        var ac = d[j].acitivtys.split(",");
        if (ac.length > 0) {
          d[j].acitivtys = "";
          for (var k = 0; k < ac.length; k++) {
            switch (ac[k]) {
              case "1":
                d[j].acitivtys += '<span class="yute zu">组</span>';
                break;
              case "2":
                d[j].acitivtys += '<span class="yute man">兑</span>';
                break;
              case "3":
                d[j].acitivtys += '<span class="yute xian">限</span>';
                break;
              case "4":
                d[j].acitivtys += '<span class="yute man">满</span>';
                break;
              case "5":
                d[j].acitivtys += '<span class="yute man">复</span>';
                break;
              case "6":
                d[j].acitivtys += '<span class="yute miao">返</span>';
                break;
              case "7":
                d[j].acitivtys += '<span class="yute tuan">拼</span>';
                break;
              case "8":
                d[j].acitivtys += '<span class="yute miao">秒</span>';
                break;
            }
          }
        }
      } else {
        d[j].acitivtys = "";
      }
    }
  }
}